#! /usr/bin/perl

use File::Basename;

BEGIN {
  unshift @INC, dirname ($0);
};

use FwRpmPackage;
use strict;

#---------------------------------------------------------------------
#                        parse_depends_range                           
# 
# Parse FW_PACKAGE_DEPENDENCIES, which is in debian binary
# dependency format.  Returns the dependencies along with 
# implied range dependencies if otherwise unspecified.
#
# NB: this version is different than the version in package/deb 
# rpm cannot handle disjunctive dependencies, so we need to pick 
# one element of the disjunction :(
# we will require the builder to have installed one of the choices
#---------------------------------------------------------------------

sub parse_depends_range ($$)
  {
    my ($state, $depends) = @_;

# libc6 (>= 2.2.1), exim | mail-transport-agent
# erlang (= INSTALLED)

    my @pkgspecs = split /,\s*/, $depends;

    my $firstspec = 1;
  SPEC:  foreach my $spec (split /,\s*/, $depends)
      {
        print ", " unless $firstspec;
        $firstspec = 0;

  OPTION: foreach my $option (split /\|\s*/, $spec)
          {
            $option =~ m/^(\S+)\s*(\(\s*(<<|<|<=|=|>=|>>)\s*([^\)]+)\))?/ or
              die "can't parse dependencies '$depends' (option '$option')\n";

            my $p = $1;
            my $op = $3;
            my $rawv = defined ($4) ? $4 : "";
            my $version = ($rawv eq "INSTALLED") ? $state->{$p} : $rawv;

            next OPTION unless exists $state->{$p};

            if (   defined ($op) && $op ne "" 
                && defined ($version) && $version ne "")
              {
                print "$p ($op $version)";
              }
            else
              {
                print "$p (>= $state->{$p})";
              }

            next SPEC;
          }

        die "can't resolve disjunction '$spec': you must install one of the choices.\n"
      }
  }

#---------------------------------------------------------------------
#                                main                                 
#---------------------------------------------------------------------

my $usage = "usage: $0 depends\n";

my $depends = $ARGV[0] or die $usage;

my ($state, undef) = get_state ();

my $packages = parse_depends_range ($state, $depends);
